package com.tarena.lbs.content.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.dao.mapper.CategoryMapper;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.pojo.po.ArticleSearchPO;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.Objects;

@Slf4j
@Repository
public class ArticleRepositoryImpl implements ArticleRepository {
    @Autowired
    private ArticleMapper articleMapper;
    
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageInfo<ArticleVO> pageList(ArticleQuery articleQuery) {
        // 使用PageHelper开始分页
        Page<ArticleSearchPO> page = PageHelper.startPage(
                articleQuery.getPageNo(),   // 当前页码
                articleQuery.getPageSize()   // 每页条数
        );

        // 构建查询条件
        QueryWrapper<ArticleSearchPO> queryWrapper = new QueryWrapper<>();
        if (articleQuery.getArticleTitle() != null && !articleQuery.getArticleTitle().trim().isEmpty()) {
            queryWrapper.like("article_title", articleQuery.getArticleTitle());
        }
        
        // 添加文章分类ID查询条件
        if (articleQuery.getArticleCategoryId() != null) {
            queryWrapper.eq("article_category_id", articleQuery.getArticleCategoryId());
        }
        
        // 添加关联活动ID查询条件
        if (articleQuery.getActivityId() != null) {
            queryWrapper.eq("activity_id", articleQuery.getActivityId());
        }
        
        // 添加更新时间范围查询条件
        if (articleQuery.getUpdateStartTime() != null) {
            queryWrapper.ge("update_time", articleQuery.getUpdateStartTime());
        }
        
        if (articleQuery.getUpdateEndTime() != null) {
            queryWrapper.le("update_time", articleQuery.getUpdateEndTime());
        }
        
        // 添加文章状态查询条件
        if (articleQuery.getArticleStatus() != null && !articleQuery.getArticleStatus().isEmpty()) {
            // 如果指定了状态，则按指定状态查询
            queryWrapper.in("article_status", articleQuery.getArticleStatus());
        } else {
            // 默认情况下，排除禁用状态（状态3）的文章，仅在推文创作时才显示状态3的文章
            queryWrapper.notIn("article_status", 3);
        }

        // 执行查询 - PageHelper会自动拦截并添加分页逻辑
        List<ArticleSearchPO> list = articleMapper.selectList(queryWrapper);

        // PO 转 VO（将数据库实体类转换为前端视图类）
        List<ArticleVO> voList = list.stream().map(po -> {
                    ArticleVO vo = new ArticleVO();
                    BeanUtils.copyProperties(po, vo); // 复制属性（需要属性名一致）
                    
                    // 如果articleCategoryId不为空，则查询对应的分类名称
                    if (po.getArticleCategoryId() != null) {
                        ArticleCategoryPO categoryPO = categoryMapper.selectById(po.getArticleCategoryId());
                        if (categoryPO != null && StringUtils.hasText(categoryPO.getCategoryName())) {
                            vo.setArticleCategory(categoryPO.getCategoryName());
                        }
                    }
                    
                    return vo;
                })
                .collect(Collectors.toList());

        // 创建PageInfo对象并复制分页信息
        PageInfo<ArticleVO> pageInfo = new PageInfo<>(voList);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setPages(page.getPages());

        return pageInfo;
    }
    
    @Override
    public PageInfo<ArticleVO> twitterPageList(ArticleQuery articleQuery) {
        // 使用PageHelper开始分页
        Page<ArticleSearchPO> page = PageHelper.startPage(
                articleQuery.getPageNo(),   // 当前页码
                articleQuery.getPageSize()   // 每页条数
        );

        // 构建查询条件
        QueryWrapper<ArticleSearchPO> queryWrapper = new QueryWrapper<>();
        if (articleQuery.getArticleTitle() != null && !articleQuery.getArticleTitle().trim().isEmpty()) {
            queryWrapper.like("article_title", articleQuery.getArticleTitle());
        }
        
        // 添加文章分类ID查询条件
        if (articleQuery.getArticleCategoryId() != null) {
            queryWrapper.eq("article_category_id", articleQuery.getArticleCategoryId());
        }
        
        // 添加关联活动ID查询条件
        if (articleQuery.getActivityId() != null) {
            queryWrapper.eq("activity_id", articleQuery.getActivityId());
        }
        
        // 添加更新时间范围查询条件
        if (articleQuery.getUpdateStartTime() != null) {
            queryWrapper.ge("update_time", articleQuery.getUpdateStartTime());
        }
        
        if (articleQuery.getUpdateEndTime() != null) {
            queryWrapper.le("update_time", articleQuery.getUpdateEndTime());
        }
        
        // 添加文章状态查询条件
        if (articleQuery.getArticleStatus() != null && !articleQuery.getArticleStatus().isEmpty()) {
            // 如果指定了状态，则按指定状态查询
            queryWrapper.in("article_status", articleQuery.getArticleStatus());
        } else {
            // 推文创作页面默认查询禁用状态（状态3）的文章
            // 但允许通过参数覆盖默认行为
            queryWrapper.in("article_status", 3);
        }

        // 执行查询 - PageHelper会自动拦截并添加分页逻辑
        List<ArticleSearchPO> list = articleMapper.selectList(queryWrapper);

        // PO 转 VO（将数据库实体类转换为前端视图类）
        List<ArticleVO> voList = list.stream().map(po -> {
                    ArticleVO vo = new ArticleVO();
                    BeanUtils.copyProperties(po, vo); // 复制属性（需要属性名一致）
                    
                    // 如果articleCategoryId不为空，则查询对应的分类名称
                    if (po.getArticleCategoryId() != null) {
                        ArticleCategoryPO categoryPO = categoryMapper.selectById(po.getArticleCategoryId());
                        if (categoryPO != null && StringUtils.hasText(categoryPO.getCategoryName())) {
                            vo.setArticleCategory(categoryPO.getCategoryName());
                        }
                    }
                    
                    return vo;
                })
                .collect(Collectors.toList());

        // 创建PageInfo对象并复制分页信息
        PageInfo<ArticleVO> pageInfo = new PageInfo<>(voList);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setPages(page.getPages());

        return pageInfo;
    }
    
    @Override
    public ArticleVO getArticleById(Integer id) {
        // 查询文章信息
        ArticleSearchPO po = articleMapper.selectById(id);
        if (po == null) {
            return null;
        }
        
        // 转换为VO对象
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(po, vo);
        
        // 如果articleCategoryId不为空，则查询对应的分类名称
        if (po.getArticleCategoryId() != null) {
            ArticleCategoryPO categoryPO = categoryMapper.selectById(po.getArticleCategoryId());
            if (categoryPO != null && StringUtils.hasText(categoryPO.getCategoryName())) {
                vo.setArticleCategory(categoryPO.getCategoryName());
            }
        }
        
        return vo;
    }
    
    @Override
    public void save(ArticleSearchPO po) {
        if (po.getId() != null) {
            articleMapper.updateById(po);
        } else {
            articleMapper.insert(po);
        }
    }
    
    @Override
    public Set<String> getAllArticleLabels() {
        List<String> labels = articleMapper.selectAllArticleLabels();
        return labels.stream().filter(Objects::nonNull).collect(Collectors.toSet());
    }
}